package cn.yunyichina.openapi.proxy.http;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

/**
 * @author zhangkewen
 */
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {

    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 40秒没有数据读入，发生超时机制
        pipeline.addLast(new ReadTimeoutHandler(40));

        // 40秒没有输入写入，发生超时机制
        pipeline.addLast(new WriteTimeoutHandler(40));

        /**
         * http-request解码器
         * http服务器端对request解码
         */
        pipeline.addLast("decoder", new HttpRequestDecoder(1024 * 1024 * 8,8192,8192));

        /**
         * http-response解码器
         * http服务器端对response编码
         */
        pipeline.addLast("encoder", new HttpResponseEncoder());

        /**
         * HttpObjectAggregator会把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse。
         */
        pipeline.addLast("aggregator", new HttpObjectAggregator(1024 * 1024 * 8));

        /**
         * 压缩
         * Compresses an HttpMessage and an HttpContent in gzip or deflate encoding
         * while respecting the "Accept-Encoding" header.
         * If there is no matching encoding, no compression is done.
         */
        pipeline.addLast("deflater", new HttpContentCompressor());

        pipeline.addLast("handler", new HttpServerHandler());
    }

}
